"use client";
import CreateModal from "./components/CreateModal";
import UpdateModal from "./components/UpdateModal";
import {
  deleteUserUsingPost,
  listUserByPageUsingPost,
} from "@/api/userController";
import { PlusOutlined } from "@ant-design/icons";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { PageContainer, ProTable } from "@ant-design/pro-components";
import { Button, message, Modal, Space, Typography } from "antd";
import React, { useRef, useState } from "react";
import MdEditor from "@/components/MdEditor";

/**
 * 用户管理页面
 *
 * @constructor
 */
const UserAdminPage: React.FC = () => {
  // 是否显示新建窗口
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  // 当前用户点击的数据
  const [currentRow, setCurrentRow] = useState<API.FunRiceUser>();

  /**
   * 删除节点
   *
   * @param row
   */

  const confirmDelete = async (record: API.FunRiceUser) => {
    Modal.confirm({
      title: "确认删除用户吗？",
      content: `确定要删除用户 ${record.userAccount} 吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        await handleDelete(record);
      },
    });
  };
  const handleDelete = async (row: API.FunRiceUser) => {
    const hide = message.loading("正在删除");
    if (!row) return true;
    try {
      await deleteUserUsingPost({
        id: row.id as any,
        userAccount: row.userAccount as any,
      });
      hide();
      message.success("删除成功");
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error("删除失败，" + error.message);
      return false;
    }
  };

  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  /**
   * 表格列配置
   */
  const columns: ProColumns<API.FunRiceUser>[] = [
    {
      title: "id",
      dataIndex: "id",
      valueType: "text",
      hideInForm: true,
    },
    {
      title: "账号",
      dataIndex: "userAccount",
      valueType: "text",
      fieldProps: {
        hideInSearch: true,
        placeholder: "账号支持查询 不支持修改",
      },
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: "用户昵称",
      dataIndex: "userName",
      valueType: "text",
      hideInSearch: true,
    },

    {
      title: "头像",
      dataIndex: "userAvatar",
      valueType: "image",
      fieldProps: {
        width: 64,
      },
      hideInSearch: true,
    },
    {
      title: "饭点们",
      dataIndex: "friendsNum",
      valueType: "text",
      hideInSearch: true,
    },
    {
      title: "简介",
      dataIndex: "userProfile",
      valueType: "text",
      hideInSearch: true,
      //markdown渲染
      renderFormItem: (
        item: ProColumns,
        // @ts-ignore
        { fieldProps },
      ) => {
        // value和onChange会通过form自动传入
        return <MdEditor {...fieldProps} />;
      },
    },
    {
      title: "角色",
      dataIndex: "userRole",
      valueType: "select",
      valueEnum: {
        0: { text: "普通用户", status: "Default" },
        1: {
          text: "管理员",
          status: "Success",
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: "非管理员 不开放设置",
          },
        ],
      },
    },
    {
      title: "会员",
      dataIndex: "vipRole",
      valueType: "select",
      valueEnum: {
        0: { text: "普通用户", status: "Default" },
        1: {
          text: "会员",
          status: "Success",
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: "非管理员 不开放设置",
          },
        ],
      },
    },
    {
      title: "会员过期时间",
      dataIndex: "vipExpireTime",
      valueType: "dateTime",
      hideInSearch: true,
    },
    {
      title: "注册时间",
      sorter: true,
      dataIndex: "createTime",
      valueType: "dateTime",
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: "更新时间",
      sorter: true,
      dataIndex: "updateTime",
      valueType: "dateTime",
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: "PW",
      sorter: true,
      dataIndex: "userPassword",
      valueType: "text",
      hideInTable: true, // 新增：在表格中隐藏
      hideInSearch: true,
      fieldProps: {
        placeholder: "如需修改密码请填写，否则留空",
      },
      formItemProps: {
        rules: [
          {
            required: false,
            message: "非管理员 不开放设置",
          },
        ],
      },
    },
    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      render: (_, record) => (
        <Space size="middle">
          <Typography.Link
            onClick={() => {
              setCurrentRow(record);
              setUpdateModalVisible(true);
            }}
          >
            修改
          </Typography.Link>

          <Typography.Link type="danger" onClick={() => confirmDelete(record)}>
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];
  return (
    <div id="admin-user" style={{
      width: '100%',
      marginTop: 0,
      display: 'flex',
      margin: '0 auto',
      marginLeft: '20px'
    }}>
      <PageContainer
          // 隐藏面包屑导航
        // breadcrumbRender={false}
        title={null}
        // 将 title 设为 null
        header={{
          title: null,
          breadcrumb: {
            items: [
              // { title: '用户管理' },
            ],
          },
        }}
      >
        <ProTable<API.FunRiceUser>
          headerTitle={null}
          options={false}
          // ghost={true} 属性，这会让表格标题区域更加简洁
          // ghost={true} 
          actionRef={actionRef}
          rowKey="key"
          search={{
            labelWidth: 80,
            defaultCollapsed: false,
            style: {
              marginBottom: '24px',
            },
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setCreateModalVisible(true);
              }}
            >
              <PlusOutlined /> 添加用户
            </Button>,
          ]}
          //@ts-ignore
          request={async (params, sort, filter) => {
            const sortField = Object.keys(sort)?.[0];
            const sortOrder = sort?.[sortField] ?? undefined;

            const { data } = await listUserByPageUsingPost({
              ...params,

              sortField: "createTime",
              sortOrder: "desc",
              ...filter,
            } as API.UserQueryRequest);
            return {
              success: true,
              data: data || [],
              total: Number(data?.data?.total) || 0,
            };
          }}
          pagination={{
            showTotal(total: number) {
              return "总数：" + total;
            },
            pageSize: 10,
          }}
          columns={columns}
          // 表格横向滚动支持
          scroll={{ x: 1400 }}
        />
        <CreateModal
          visible={createModalVisible}
          columns={columns}
          onSubmit={() => {
            setCreateModalVisible(false);
            actionRef.current?.reload();
          }}
          onCancel={() => {
            setCreateModalVisible(false);
          }}
        />
        <UpdateModal
          visible={updateModalVisible}
          columns={columns}
          oldData={currentRow}
          onSubmit={() => {
            setUpdateModalVisible(false);
            setCurrentRow(undefined);
            actionRef.current?.reload();
          }}
          onCancel={() => {
            setUpdateModalVisible(false);
          }}
        />
      </PageContainer>
    </div>
  );
};
export default UserAdminPage;
